<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="90%"
    top="5vh"
    :close-on-click-modal="false"
    :append-to-body="true"
    @close="handleClose"
  >
    <div class="location-container">
      <!-- 顶部操作栏 -->
      <div class="toolbar">
        <el-form :inline="true" :model="queryForm" size="small">
          <el-form-item>
            <el-input
              v-model="queryForm.stoUnitCode"
              placeholder="货位编码"
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryForm.enableState" placeholder="状态" clearable style="width: 120px;">
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="action-buttons">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增货位</el-button>
          <el-button type="success" size="small" icon="el-icon-circle-plus" @click="handleContinueAdd">续增货位
          </el-button>
          <el-button type="info" size="small" icon="el-icon-printer" @click="handlePrint">打印</el-button>
          <el-button type="success" size="small" icon="el-icon-video-play" @click="handleBatchEnable">批量启用
          </el-button>
          <el-button type="warning" size="small" icon="el-icon-video-pause" @click="handleBatchDisable">批量停用
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
        </div>
      </div>

      <!-- 货位表格 -->
      <el-table
        :data="locationList"
        border
        stripe
        height="500px"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="stoUnitCode" label="货位编码" min-width="120" align="center"/>
        <el-table-column prop="stoName" label="所属库房" min-width="110" align="center"/>
        <el-table-column prop="stoAreaName" label="所属库区" min-width="110" align="center"/>
        <el-table-column prop="enableState" label="状态" width="80" align="center">
          <template slot-scope="scope">
            <el-switch
              :value="scope.row.enableState"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              @change="handleToggleStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间" width="190" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              style="color: #F56C6C;"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 新增/编辑货位对话框 -->
    <el-dialog
      :title="formDialogTitle"
      :visible.sync="formDialogVisible"
      width="800"
      append-to-body
      @close="handleFormClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="货架号/货架数" :label-width="formLabelWidth" prop="flag">
              <el-switch v-model="form.flag" active-text="货架号" inactive-text="货架数" :active-value="'1'"
                         :inactive-value="'0'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位类型" :label-width="formLabelWidth" prop="def1">
              <el-select clearable v-model="form.def1" style="width: 100%;" placeholder="请输入货位类型">
                <el-option v-for="(item, index) in areaList" :key="index" :value="item.tag" :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货架层数" :label-width="formLabelWidth" prop="layerCount">
              <el-input v-model="form.layerCount" placeholder="请输入货架层数"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="层货位数" :label-width="formLabelWidth" prop="positionsPerLayer">
              <el-input v-model="form.positionsPerLayer" placeholder="请输入层货位数"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.flag == '0'?'货架数量':'货架号'" :label-width="formLabelWidth" prop="def2">
              <el-input v-model="form.def2" placeholder="请输入数量"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="formDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFormSubmit" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 续增货位对话框 -->
    <el-dialog
      title="续增货位"
      :visible.sync="continueAddDialogVisible"
      width="600px"
      append-to-body
      @close="handleContinueAddClose"
    >
      <el-form ref="continueAddFormRef" :model="continueAddForm" :rules="continueAddRules" label-width="100px">
        <el-form-item label="货位选择" prop="stoUnitCode">
          <el-select
            v-model="continueAddForm.stoUnitCode"
            filterable
            placeholder="请选择需要续增的货位"
            style="width: 100%;"
          >
            <el-option
              v-for="(item, index) in allCodeAdd"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="增加个数" prop="number">
          <el-input-number
            v-model="continueAddForm.number"
            :min="1"
            :max="999"
            placeholder="请输入增加的个数"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="enableState">
          <el-switch
            v-model="continueAddForm.enableState"
            active-text="启用"
            inactive-text="停用"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleContinueAddClose">取 消</el-button>
        <el-button type="primary" @click="handleContinueAddSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 打印对话框 -->
    <LocationPrintDialog ref="printDialogRef"/>
  </el-dialog>
</template>

<script>
import {
  locationOperation,
  locationAddOperation,
  locationEditOperation,
  deleteByStoUnitId,
  batchDeleteByStoUnitId,
  updateBasicStoUnitEnableStatus,
  updateBasicStoUnitEnableStatusAll,
  getAllStoUnitCode,
  addStoUnitStorage,
  basicStoShelf

} from '@/api/index/warehouse';
import LocationPrintDialog from './LocationPrintDialog.vue';

export default {
  name: 'LocationDialog',
  components: {
    LocationPrintDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    areaInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateDef2 = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('货架数量不能为空'));
      }
      if (this.isGroundStack) {
        if (!/^[a-zA-Z0-9]+$/.test(value)) {
          callback(new Error('只能输入字母和数字，不能输入中文'));
        } else {
          callback();
        }
      } else {
        if (!/^\d+$/.test(value)) {
          callback(new Error('只能输入整数'));
        } else {
          callback();
        }
      }
    };
    return {
      formLabelWidth: '100px',
      dialogVisible: false,
      loading: false,
      locationList: [],
      total: 0,
      queryForm: {
        stoUnitCode: '',
        enableState: '',
        pageNum: 1,
        pageSize: 20
      },
      selectedRows: [],

      // 表单对话框
      formDialogVisible: false,
      formType: 'add',
      submitLoading: false,
      form: {
        positionsPerLayer: '',
        layerCount: '',
        def1: '',
        def2: '',
        enableState: '0',
        flag: '0'
      },
      areaList: [],//货位类型
      rules: {
        def1: [{
          required: true,
          message: '货位类型不能为空',
          trigger: 'change',
        }],
        def2: [{
          required: true,
          message: '货架数量不能为空',
        }, {
          validator: validateDef2,
          trigger: 'blur'
        }],
        positionsPerLayer: [{
          required: true,
          message: '层货位数',
          trigger: 'blur'
        }],
        layerCount: [{
          required: true,
          message: '货架层数不能为空',
          trigger: 'blur'
        }],
      },

      // 续增对话框
      continueAddDialogVisible: false,
      allCodeAdd: [],
      continueAddForm: {
        stoUnitCode: '',
        number: null,
        enableState: '1'
      },
      continueAddRules: {
        stoUnitCode: [
          {required: true, message: '请选择货位', trigger: 'change'}
        ],
        number: [
          {required: true, message: '请输入增加个数', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur'}
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      const areaName = this.areaInfo.stoAreaName || this.areaInfo.sto_area_name || '';
      return areaName ? `${areaName} - 货位管理` : '货位管理';
    },
    formDialogTitle() {
      return this.formType === 'add' ? '新增货位' : '编辑货位';
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) {
        this.getList();
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  created() {
    this.getArea();
  },
  methods: {
    //获取货位类型
    getArea() {
      basicStoShelf().then(res => {
        this.areaList = res.rows;
      })
    },
    // 获取货位列表
    getList() {
      this.loading = true;
      const params = {
        ...this.queryForm,
        stoId: this.areaInfo.stoId,
        stoAreaId: this.areaInfo.stoAreaId || this.areaInfo.sto_area_id
      };
      locationOperation(params).then(res => {
        this.locationList = res.rows || res.data || [];
        this.total = res.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 查询
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },

    // 重置
    handleReset() {
      this.queryForm = {
        stoUnitCode: '',
        enableState: '0',
        pageNum: 1,
        pageSize: 20
      };
      this.getList();
    },

    // 分页
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.queryForm.pageNum = val;
      this.getList();
    },

    // 选择
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 新增
    handleAdd() {
      this.formType = 'add';
      this.form = {
        stoAreaId: this.areaInfo.stoAreaId,
        stoId: this.areaInfo.stoId,
        enableState: '0'
      };
      this.formDialogVisible = true;
    },
    // 提交表单
    handleFormSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          const apiMethod = this.formType === 'add' ? locationAddOperation : locationEditOperation;
          apiMethod(this.form).then(res => {
            this.$message.success(res.msg || '操作成功');
            this.submitLoading = false;
            this.formDialogVisible = false;
            this.getList();
          }).catch(err => {
            this.$message.error(err.msg || '操作失败');
            this.submitLoading = false;
          });
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该货位吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteByStoUnitId({stoUnitId: row.stoUnitId}).then(() => {
          this.$message.success('删除成功');
          this.getList();
        });
      }).catch(() => {
      });
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的货位');
        return;
      }
      this.$confirm(`确定要删除选中的 ${this.selectedRows.length} 个货位吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(item => item.stoUnitId);
        batchDeleteByStoUnitId(ids).then(() => {
          this.$message.success('删除成功');
          this.getList();
        });
      }).catch(() => {
      });
    },
    // 任务状态修改
    handleToggleStatus(row) {
      // 临时保存当前状态，以便取消时恢复
      const currentState = row.enableState;
      // 根据 enableState 判断是启用还是停用
      let text = row.enableState === "1" ? "停用" : "启用";
      let query = {
        enableState: currentState === "1" ? "0" : "1", // 状态切换：如果是 "0"（禁用），则切换为 "1"（启用）；反之亦然
        stoUnitId: row.stoUnitId,
        stoUnitCode:row.stoUnitCode
      }
      // 弹出确认框
      this.$confirm(`确认要${text}此项任务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 更新状态
        updateBasicStoUnitEnableStatus(query).then(res => {
          // 显示成功消息
          this.$message({
            type: 'success',
            message: `${text}成功!` // 根据操作状态来动态显示消息
          });
          this.getList();
        }).catch(error => {
          // 恢复原始状态
          row.enableState = currentState;
        });
      }).catch(() => {
        // 用户取消了操作，恢复原始状态
        this.$message({
          type: 'info',
          message: '操作已取消'
        });
        row.enableState = currentState; // 恢复原始状态
      });
    },
    // 续增货位
    handleContinueAdd() {
      if (!this.areaInfo.stoAreaId && !this.areaInfo.sto_area_id) {
        this.$message.warning('请先选择库区');
        return;
      }
      this.continueAddDialogVisible = true;
      this.getAllCode();
    },

    // 获取货位编码下拉数据
    getAllCode() {
      const params = {
        stoId: this.areaInfo.stoId || this.areaInfo.sto_id
      };
      getAllStoUnitCode(params).then(res => {
        this.allCodeAdd = res.data || [];
      });
    },

    // 提交续增
    handleContinueAddSubmit() {
      this.$refs.continueAddFormRef.validate((valid) => {
        if (valid) {
          const data = {
            ...this.continueAddForm,
            stoId: this.areaInfo.stoId || this.areaInfo.sto_id,
            stoAreaId: this.areaInfo.stoAreaId || this.areaInfo.sto_area_id
          };
          addStoUnitStorage(data).then(res => {
            this.$message.success(res.msg || '续增成功');
            this.continueAddDialogVisible = false;
            this.getList();
          });
        }
      });
    },

    // 关闭续增对话框
    handleContinueAddClose() {
      this.continueAddDialogVisible = false;
      this.$nextTick(() => {
        this.$refs.continueAddFormRef && this.$refs.continueAddFormRef.resetFields();
      });
    },

    // 打印
    handlePrint() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要打印的货位');
        return;
      }
      // 打开高级打印对话框
      this.$refs.printDialogRef.open(this.selectedRows);
    },

    // 批量启用
    handleBatchEnable() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要启用的货位');
        return;
      }

      let param = {
        status: 1
      };
      const ids = this.selectedRows.map(item => item.stoUnitId || item.sto_unit_id);
      updateBasicStoUnitEnableStatusAll(ids, param).then(() => {
        this.$message.success('批量启用成功');
        this.getList();
      });
    },


    // 批量停用
    handleBatchDisable() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要停用的货位');
        return;
      }
      let param = {
        status: 0
      };
      const ids = this.selectedRows.map(item => item.stoUnitId || item.sto_unit_id);
      updateBasicStoUnitEnableStatusAll(ids, param).then(() => {
        this.$message.success('批量停用成功');
        this.getList();
      });
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false;
    },

    // 关闭表单对话框
    handleFormClose() {
      this.$refs.formRef.resetFields();
    }
  }
};
</script>

<style scoped lang="scss">
.location-container {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .action-buttons {
      display: flex;
      gap: 8px;
    }
  }

  .pagination {
    margin-top: 16px;
    text-align: right;
  }
}
</style>
